import { onBeforeUpdate, ref } from "vue";
import { getOssSignForWeb, uploadFile } from "@/api/methods/upload";

/**
 * 绑定ref
 * example:https://cool-js.com/uni/hooks/useCool.html#refs
 * @returns {{refs: Ref<UnwrapRef<{}>>, setRefs: (function(*): function(*): void)}}
 */
export function useRefs() {
  const refs = ref({});

  onBeforeUpdate(() => {
    refs.value = {};
  });

  const setRefs = (index) => {
    return (el) => {
      refs.value[index] = el;
    };
  };

  return { refs, setRefs };
}

/**
 * 上传文件
 * @param url
 */
export const uploadFilePromise = (url, fileType = 'image') => {
  return new Promise((resolve) => {
    getOssSignForWeb().then(async (data) => {
      const key = `${data.dir}_${+new Date()}.${url.split(".").pop()}`;
      const sendData = {
        url: data.host,
        filePath: url,
        fileType,
        formData: {
          key,
          policy: data.policy, // 后台获取超时时间
          OSSAccessKeyId: data.accessid, // 后台获取临 时ID
          success_action_status: "200", // 让服务端返回200,不然，默认会返回204
          signature: data.signature, // 后台获取签名
        },
      };
      const success = await uploadFile(sendData);
      if (success) {
        resolve(key);
      }
    });
  });
};
